package com.tianhui.consignortwofei.mvp.ui.activity.hetong;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.fgs.common.CommonResponse;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.LogUtil;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.api.hetong.HuRequest;
import com.tianhui.consignortwofei.constant.Config;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractInfo;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractModel;
import com.tianhui.consignortwofei.mvp.model.hetong.ShenPiTiJiaoOneBean;
import com.tianhui.consignortwofei.mvp.ui.activity.HeTongWatchActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.ShenHeWatchOneActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.activity.ContractAddStepOneActivityNew;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.adapter.ShenContractListAdapter;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.contract.ContractListContract;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.impl.HeTongIOrderStatus;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.other.IContractType;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.presenter.ContractListPresenter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/8/27
 * @description
 **/
public class ShenContractListFragment extends HeTongSearchFragment<ContractListContract.View, ContractListContract.Presenter> implements ContractListContract.View {

    private HeTongIOrderStatus mIOrderStatus;
    private String mSearchKey;
    private String mYinCangWitch="";

    private ContractModel contractModel;
    private HuRequest huRequest;

    public ShenContractListFragment() {
        // Required empty public constructor
        contractModel = new ContractModel();
    }

    @Override
    public boolean isNeedLazyLoad() {
        return false;
    }

    public static ShenContractListFragment newInstance(HeTongIOrderStatus iOrderStatus) {
        ShenContractListFragment orderListFragment = new ShenContractListFragment();
        orderListFragment.setOrderStatus(iOrderStatus);

        return orderListFragment;
    }

    public ShenContractListFragment setOrderStatus(HeTongIOrderStatus iOrderStatus) {
        mIOrderStatus = iOrderStatus;
        return this;
    }

    public ShenContractListFragment setSearchKey(String searchKey) {
        mSearchKey = searchKey;
        return this;
    }

    public ShenContractListFragment setWitch(String witch) {
        mYinCangWitch = witch;
        return this;
    }


    @Override
    protected ContractListContract.View createView() {
        huRequest = new HuRequest();
        return this;
    }

    @Override
    protected ContractListContract.Presenter createPresenter() {
        return new ContractListPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new ShenContractListAdapter(getContext(), mIOrderStatus,mYinCangWitch);
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object object = mAdapter.getAllData().get(position);
                ContractInfo contractInfo = null;
                if (object instanceof ContractInfo) {
                    contractInfo = (ContractInfo) object;
                }
                switch (view.getId()) {
                    case R.id.item_contract_list_createTextView:
                        //审核
//                        showCreateTipDialog(contractInfo);
//                        if (contractInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("danHao", contractInfo.contractno);
////                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
////                            openActivity(LiuChengJieDianActivity.class, bundle);//流程显示
//                            openActivity(HeTongShenPiBossActivity.class, bundle);//审核页面
//                        }
                        if (contractInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
                            openActivity(ShenHeWatchOneActivity.class, bundle);//审核页面
                        }

                        break;
                    case R.id.item_contract_list_downloadTextView:
                      //查看流程
//                        downloadContract(contractInfo);
                        if (contractInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
                            openActivity(LiuChengJieDianActivity.class, bundle);//流程显示
                        }
                        break;
                    case R.id.item_contract_list_editTextView:
                        showCreateTipDialog(contractInfo);//生成合同
//                        if (contractInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
////                            openActivity(EditContractStepOneActivity.class, bundle);
//                            openActivity(EditContractStepOneActivityNew.class, bundle);
//                        }
                        break;
                    case R.id.item_contract_list_watch:
                        if (contractInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
//                            openActivity(EditContractStepOneActivity.class, bundle);
                            openActivity(HeTongWatchActivity.class, bundle);//查看合同
//                            openActivity(LiuChengJieDianActivity.class, bundle);//流程显示
//                            openActivity(HeTongShenPiBossActivity.class, bundle);//审核页面


                        }
                        break;


                }
            }
        });

    }

    private void showCreateTipDialog(ContractInfo contractInfo) {
        new MaterialDialog.Builder(getContext())
                .content("是否生成提交？")
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        createContract(contractInfo);
                    }
                })
                .show();
    }

    private void downloadContract(ContractInfo contractInfo) {
        String url = Config.baseUrl + "contract/download?id=" + contractInfo.id;
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void createContract(ContractInfo contractInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", contractInfo.id);
        map.put("type", "1");
        contractModel.createContractModel(getContext(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                showToast(commonResponse.getMsg());
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }


    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.page = page;
            orderCondition.searchKey = mSearchKey;
            getPresenter().requestOrderList(mIOrderStatus.getOrderListObservable(orderCondition), isDialog,huRequest,page);
        }
    }

    @Override
    public void initData() {
//        String consignorName = SharedPreferenceManager.getInstance().getConsignorName();
//        if ("徐飞".equals(consignorName)) {
//            if (TextUtils.isEmpty(mYinCangWitch)){
//                tv_shenhe.setVisibility(View.VISIBLE);
//            }
//        }

        if (mIOrderStatus != null) {
            setSearchKeyHint(mIOrderStatus.getSearchHint());
        }

        fragment_contract_list_addContractButton.setVisibility(View.GONE);

    }

    @Override
    protected void requestSearch(String searchKey) {
        mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_CONTRACT_LIST:
                if (isHasLoadData())
                    mAdapter.removeAll();
                    refreshData(true);
                break;
            case CHANGE_TAB_FRAGMENT:
        }
    }

    @OnClick(R.id.fragment_contract_list_addContractButton)
    public void addContract() {
        openActivity(ContractAddStepOneActivityNew.class);
//        openActivity(ContractAddStepOneActivity.class);
//        openActivity(ContractAddStepFourActivity.class);
    }


//    private long exitTime = 0;
    //自动审核
    @OnClick(R.id.tv_shenhe)
    public void shenHe() {

//        long now = System.currentTimeMillis();
//        if (now - exitTime < 2000) {
//            showToast("已点击一次了");
//            return;
//        }
//        exitTime = now;

        showToast("开始执行");

        List<ContractInfo> allList = mAdapter.getAllData();
        fujianMsg="";
//        getShenHeInfo(allList.get(0));
        for (int i=0;i<allList.size();i++){
            ContractInfo mContractInfo = allList.get(i);
            getShenHeInfo(mContractInfo);

        }

        //刷新列表
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO
                try {
                    if (!getActivity().isFinishing()) {
                        refreshData(true);
                    }
                }catch (Exception e){
                    LogUtil.print(e.toString());
                }

            }
        }, 3000);



    }


    private UserInfoModel driverModel;
    private ShenPiTiJiaoOneBean shenPiTiJiaoOneBean;
    private String wudingjin="双方约定可分批交货，按每批交货数量的全额货值付款，所有办款时间均为货到当天内;如因乙方原因导致超出约定时间未进行货物交付，则乙方需自合同约定交付日起2日内将全部货款支付给甲方，甲方收到货款当日变更货物交付方式为转货权给客户，如条件不允许转货权，则自合同约定交付日起货物产生的相关费用包括但不限于仓储费用、装卸费用、货转费用等均由需方承担，在此期间货物发生毁损等损失也应由需方承担。";
    private String youdingjin="，尾款于提货前付清。双方可约定可分批交货，按每批交货数量的全额货值付款，定金在尾款结算时使用，所有办款时间均为货到当天;如因乙方原因导致超出约定时间未进行货物交付，则乙方需自合同约定交付日起2日内将全部货款支付给甲方，甲方收到货款当日进行货物交付或者协商变更货物交付方式为转货权给乙方，如条件不允许转货权，则自合同约定交付日起货物产生的相关费用包括但不限于仓储费用、装卸费用、货转费用等均由乙方承担，在此期间货物发生毁损等损失也应由乙方承担。";
    private void getShenHeInfo(ContractInfo contractInfo) {
        if (null==driverModel){
            driverModel = new UserInfoModel();
        }
        Map<String, String> map = new HashMap<>();
        map.put("type","2");
        map.put("contractno",contractInfo.contractno);
        driverModel.getShenHeInfo(getActivity(), map, true, this.bindLifecycle(),
                new ObserverResponseListener<CommonResponse<ShenPiTiJiaoOneBean>>() {
                    @Override
                    public void onNext(CommonResponse<ShenPiTiJiaoOneBean> commonResponse) {
                            if (commonResponse.getCode() == 20000) {
                                shenPiTiJiaoOneBean = commonResponse.getData();

                                shenPiTiJiaoOneBean.setContractno(contractInfo.contractno);
//                                String last = shenPiTiJiaoOneBean.getLast();
//                                if("1".equals(last)){
//                                    tv_zhongshen.setVisibility(View.VISIBLE);
//                                }else {
//                                    tv_zhongshen.setVisibility(View.GONE);
//                                }
//
//                                if ("1".equals(shenPiTiJiaoOneBean.getEnd())){//总裁隐藏终审
//                                    tv_zhongshen.setVisibility(View.GONE);
//                                    civ_duixiang.setVisibility(View.GONE);
//                                }
//
//                                civ_jiedian.setContent(shenPiTiJiaoOneBean.getName());
//                                civ_duixiang.setContent(shenPiTiJiaoOneBean.getPlanusername());
//                                shenPiTiJiaoOneBean.setPlanuser("43730");
//                                shenPiTiJiaoOneBean.setPlanuser(shenPiTiJiaoOneBean.getPlanuser());



                                if (!TextUtils.isEmpty(contractInfo.contracttype)) {
                                    if (contractInfo.contracttype.equals(IContractType.ADVANCE_PAYMENT)) {
                                        //先款

                                        //终审
                                        shenPiTiJiaoOneBean.setRemark("");
                                        shenPiTiJiaoOneBean.setStatus("1");
                                        shenPiTiJiaoOneBean.setFinals("1");
                                        postShenHeInfo();


                                    } else if (contractInfo.contracttype.equals(IContractType.CASH_DEPOSIT)) {
                                        //现货有定金
                                        try {
                                            String payway = contractInfo.payway;
                                            String[] yuan = payway.split("元");
                                            String shuzi = yuan[0];
                                            String tiaokuan = yuan[1];

                                            boolean hasNumber = containsNumber(shuzi);
                                            boolean hasWan = shuzi.contains("万");
                                            boolean hasQian = shuzi.contains("千");
                                            boolean hasBai = shuzi.contains("百");

//                                            String[] tiaokuanSplit = tiaokuan.split("前付清");
//                                            String tiaokuanTwo = tiaokuanSplit[1];


                                            if (hasNumber||hasWan||hasQian||hasBai){

//                                                if (youdingjin.equals(tiaokuan)){
                                                    //终审
                                                    shenPiTiJiaoOneBean.setRemark("");
                                                    shenPiTiJiaoOneBean.setStatus("1");
                                                    shenPiTiJiaoOneBean.setFinals("1");
                                                    postShenHeInfo();
//                                                }else {
//                                                    //修改了第五条
////                                                    if (TextUtils.isEmpty(shenPiTiJiaoOneBean.getFirstRemark())){
////                                                        //驳回
////                                                        shenPiTiJiaoOneBean.setRemark("提交时将修改条款原因填写到备注");
////                                                        shenPiTiJiaoOneBean.setStatus("2");
////                                                        postShenHeInfo();
////                                                    }else {
////                                                        showFuJianLog(contractInfo.contractno,shenPiTiJiaoOneBean.getFirstRemark());
////                                                    }
//
//                                                    showFuJianLog(contractInfo.contractno,"");
//
////                                                    //正常审核
////                                                    if (null == shenPiTiJiaoOneBean.getPlanuser() || TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())) {
////                                                        showToast("请选择审批对象");
////                                                        return;
////                                                    }
////                                                    shenPiTiJiaoOneBean.setRemark("");
////                                                    shenPiTiJiaoOneBean.setStatus("1");
////                                                    postShenHeInfo();
//                                                }


                                            }else {
                                                //驳回
                                                shenPiTiJiaoOneBean.setRemark("未填写订金");
                                                shenPiTiJiaoOneBean.setStatus("2");
                                                postShenHeInfo();
                                            }
                                        }catch (Exception e){
                                            showToast("期货有定金错误,元未识别出来");
                                            //终审
                                            shenPiTiJiaoOneBean.setRemark("");
                                            shenPiTiJiaoOneBean.setStatus("1");
                                            shenPiTiJiaoOneBean.setFinals("1");
                                            postShenHeInfo();

                                        }


                                    } else if (contractInfo.contracttype.equals(IContractType.NO_CASH_DEPOSIT)) {
                                        //现货无定金
//                                        if (wudingjin.equals(contractInfo.payway)){
                                            //终审
                                            shenPiTiJiaoOneBean.setRemark("");
                                            shenPiTiJiaoOneBean.setStatus("1");
                                            shenPiTiJiaoOneBean.setFinals("1");
                                            postShenHeInfo();
//                                        }else {
//                                            //修改了第五条
////                                            if (TextUtils.isEmpty(shenPiTiJiaoOneBean.getFirstRemark())){
////                                                //驳回
////                                                shenPiTiJiaoOneBean.setRemark("提交时将修改条款原因填写到备注");
////                                                shenPiTiJiaoOneBean.setStatus("2");
////                                                postShenHeInfo();
////                                            }else {
////                                                showFuJianLog(contractInfo.contractno,shenPiTiJiaoOneBean.getFirstRemark());
////                                            }
//
//                                            showFuJianLog(contractInfo.contractno,"");
//
////                                            //正常审核
////                                            if (null == shenPiTiJiaoOneBean.getPlanuser() || TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())) {
////                                                showToast("请选择审批对象");
////                                                return;
////                                            }
////                                            shenPiTiJiaoOneBean.setRemark("");
////                                            shenPiTiJiaoOneBean.setStatus("1");
////                                            postShenHeInfo();
//                                        }

                                    } else if (contractInfo.contracttype.equals(IContractType.FUTURES_DEPOSIT)) {
                                        //期货有定金
                                        //正常审核
                                        if (null == shenPiTiJiaoOneBean.getPlanuser() || TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())) {
                                            showToast("请选择审批对象");
                                            return;
                                        }
                                        shenPiTiJiaoOneBean.setRemark("");
                                        shenPiTiJiaoOneBean.setStatus("1");
                                        postShenHeInfo();

                                    } else if (contractInfo.contracttype.equals(IContractType.ACCOUNTING_PERIOD)) {
                                        //账期
                                        //正常审核
                                        if (null == shenPiTiJiaoOneBean.getPlanuser() || TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())) {
                                            showToast("请选择审批对象");
                                            return;
                                        }
                                        shenPiTiJiaoOneBean.setRemark("");
                                        shenPiTiJiaoOneBean.setStatus("1");
                                        postShenHeInfo();

                                    }else if (contractInfo.contracttype.equals(IContractType.DIAN_JIA)) {
                                        //点价
                                        //正常审核
                                        if (null == shenPiTiJiaoOneBean.getPlanuser() || TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())) {
                                            showToast("请选择审批对象");
                                            return;
                                        }
                                        shenPiTiJiaoOneBean.setRemark("");
                                        shenPiTiJiaoOneBean.setStatus("1");
                                        postShenHeInfo();

                                    }

                                }



                            } else {
                                showToast(commonResponse.getMsg());
                            }

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {

                        showToast(e.message);
                    }
                });
    }



    private void postShenHeInfo() {
        driverModel.postShenHeIsTong(getActivity(), shenPiTiJiaoOneBean, true, this.bindLifecycle(),
                new ObserverResponseListener<CommonResponse>() {
                    @Override
                    public void onNext(CommonResponse commonResponse) {
                            if (commonResponse.getCode() == 20000) {
//                                EventBusManage.refreshContractList();
//                                openActivity(HeTongShenTwoActivity.class);

                            } else {
                                showToast(commonResponse.getMsg());
                            }

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {

                        showToast(e.message);
                    }
                });
    }

    //判断字符串中是否含有数字
    private boolean containsNumber(String input) {
        Pattern pattern = Pattern.compile("\\d");
        Matcher matcher = pattern.matcher(input);
        return matcher.find();
    }



    private MaterialDialog fuJianDialog;
    private String fujianMsg="";
    private void showFuJianLog(String fuJianNum,String msg) {

        fujianMsg=fujianMsg+"\n"+fuJianNum;//+"\n"+msg;
        if (null!=fuJianDialog) {
            fuJianDialog.dismiss();
        }
        fuJianDialog = new MaterialDialog.Builder(getContext())
                .content(fujianMsg)
                .title("修改了合同第五条")
                .negativeText("关闭")
                .positiveText("查看")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                })
                .show();


    }


}
